package com.agp.controller.common;

import com.agp.constant.MessageConstant;
import com.agp.constant.SMSConstant;
import com.agp.context.BaseContext;
import com.agp.dto.AncientTreePageQueryDTO;
import com.agp.entity.Menu;
import com.agp.exception.CaptchaFrequentException;
import com.agp.result.PageResult;
import com.agp.result.Result;
import com.agp.service.MenuService;
import com.agp.service.TreeMediaService;
import com.agp.service.TreeService;
import com.agp.service.UserService;
import com.agp.utils.AliOssUtil;
import com.agp.utils.SMSUtil;
import com.agp.vo.MarkerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "共同接口")
public class CommonController {
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private TreeMediaService treeMediaService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private TreeService treeService;

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/sendCaptcha")
    @ApiOperation("发送验证码接口")
    public Result register(@NotBlank(message = "手机号不能为null、空字符串和空白串")
                           @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式错误")
                           String phone) {
        log.info("手机号码：{}", phone);
        Long count = redisTemplate.boundValueOps(SMSConstant.SMS_COUNT + phone).increment(1);
        // 5分钟内连续发送5次短信，则发送频繁
        if (count > 3) {
            log.info("验证码发送频繁,超过了限定的次数");
            throw new CaptchaFrequentException(MessageConstant.CAPTCHA_FREQUENT);
        }
        // 生成验证码
        String smsCode = smsUtil.getSMSCode();
        log.info("验证码：{}", smsCode);
        if (count == 1) {
            redisTemplate.expire(SMSConstant.SMS_COUNT + phone, SMSConstant.SMS_EXPIRE_TIME, TimeUnit.SECONDS);
        }
        redisTemplate.opsForValue().set(SMSConstant.SMS_PHONE + phone, smsCode, SMSConstant.SMS_EXPIRE_TIME, TimeUnit.SECONDS);

        // 2. 发送验证码
        //smsUtil.sentCaptcha(phone,smsCode);
        return Result.success();
    }


   /**
     * 文件上传
     *
     * @param file 文件
     * @param treeId 树木id
     * @return
     */
    @PostMapping("/uploadTree/{treeId}")
    @ApiOperation("树木图片文件上传")
    public Result<List<String>> upload(MultipartFile[] file, @PathVariable Integer treeId) throws Exception {
        log.info("文件上传{},树木id{}", file, treeId);
        List<String> urls = aliOssUtil.uploadFile(file,treeId, "admin");
        //treeMediaService.save(urls, treeId);
        return Result.success(urls);
    }

    /**
     * 上传用户头像文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadUser")
    @ApiOperation("用户头像文件上传")
    public Result<String> uploadUserImage(MultipartFile[] file) throws Exception {
        Long userId = BaseContext.getCurrentId();
        log.info("文件上传{}", file);
        List<String> urls = aliOssUtil.uploadFile(file, userId);
        return Result.success(urls.get(0));
    }


    /**
     * 根据角色查菜单
     *
     * @return
     */
    @GetMapping("/menu")
    @ApiOperation("查询菜单接口")
    public Result<List<Menu>> getMenuByRole(){
        log.info("根据角色查菜单接口");
        //
        Long currentId = BaseContext.getCurrentId();
        log.info("当前用户id为：{}",currentId);
        Integer role=userService.getRoleById(currentId);
        log.info("当前用户角色为：{}",role);
        List<Menu> menu = menuService.getMenuByRole(role);
        log.info("菜单为：{}",menu);
        return Result.success(menu);
    }


    @PostMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> page(@RequestBody AncientTreePageQueryDTO pageQueryDTO){
        log.info("分页查询{}", pageQueryDTO);
        PageResult pageResult =  treeService.page(pageQueryDTO);
        return Result.success(pageResult);
    }
    /**
     * 获取所有古树标记所需要的信息
     * @return
     */
    @GetMapping("/marker")
    @ApiOperation("获取所有古树标记所需要信息")
    public Result<List<MarkerVO>> getMarker(){
        log.info("获取所有古树标记所需要信息");
        List<MarkerVO> markerVOList = treeService.getMarker();
        return Result.success(markerVOList);
    }
}
